const Router = require('koa-router')
const { Metadata } = require('../database/models/metadata')
const { MetamapExpression } = require('../database/models/metamapExpression')
const { OrganVirusData } = require('../database/models/organVirusData')
const { QueryTypes } = require('sequelize')
const { sequelize } = require('../database/db')
const uploadExcelSrv = require('../uilt/uploadExcelSrv')
const check = require('../pem/check')

let router = new Router()

router.post('/', async(ctx) => {
    const { timestamp, type } = ctx.request.body
    const { file, fileName } = ctx.uploadpath
    if (file) {
        const verify = await check(ctx.request.headers.authorization)
        if (verify) {
            const res = await uploadExcelSrv('.' + file, type)
            if (res.s) {
                try {
                    const list = res.m.map((v, i) => {
                        v.id = (i + 1) + ''
                        return v
                    })
                    if(type === 'metadata') {
                        await Metadata.destroy({where: {}, truncate: true})
                        const arr = Datas(list, 10000)
                        for (let i = 0; i < arr.length; i++) {
                            await Metadata.bulkCreate(
                                arr[i],
                                {
                                    updateOnDuplicate:[
                                        'id', 'System', 'Tissue', 'VirusTaxonomyID',
                                        'SampleID', 'Gender', 'AgeGroup', 'Age',
                                        'Country', 'Race', 'CollectionDate'
                                    ]
                                }
                            )
                        }
                    } else if (type === 'metamapExpression') {
                        await MetamapExpression.destroy({where: {}, truncate: true})
                        await MetamapExpression.bulkCreate(
                            list,
                            {
                                updateOnDuplicate:[
                                    'id', 'System', 'Organ', 'VirusFamily',
                                    'VirusName', 'VirusTaxonomy', 'Expression'
                                ]
                            }
                        )
                    } else {
                        await OrganVirusData.destroy({where: {}, truncate: true})
                        await OrganVirusData.bulkCreate(
                            list,
                            {
                                updateOnDuplicate: [
                                    'id', 'System', 'Organ', 'VirusFamily', 'VirusName',
                                    'VirusTaxonomy', 'Evidence', 'Kingdom', 'Phylum',
                                    'Class', 'Order', 'Family', 'Genus', 'Species',
                                    'NucleicAcidType'
                                ]
                            }
                        )
                    }
                    const data = await sequelize.query(
                        `INSERT INTO Basedata (fileName, path, timestamp, type) VALUES ('${fileName}', '${file}', '${timestamp}', '${type}')`
                    );
                    ctx.body = {
                        code: 101,
                        data: {
                            id: data[0],
                            fileName,
                            path: file,
                            timestamp,
                            type
                        },
                        msg: '成功'
                    }
                } catch(err){
                    console.log(err.message)
                    ctx.body = {
                        code: 102,
                        data: 1,
                        msg: err.message
                    }
                }
            } else {
                ctx.body = {
                    code: 102,
                    data: 2,
                    msg: res.m
                }
            }
        } else {
            ctx.body = {
                code: 201,
                data: null,
                msg: 'token过期'
            }
        }
    } else {
        ctx.body = {
            code: 102,
            data: null,
            msg: ''
        }
    }
})

router.get('/list', async(ctx) => {
    const data = await sequelize.query(
        `SELECT * FROM Basedata`,
        { type: QueryTypes.SELECT }
    );
    ctx.body = {
        code: 101,
        data,
        msg: ''
    }
})

function Datas(data, num) {
    let index = 0
    let array = []
    while(index < data.length) {
        array.push(data.slice(index, index += num));
    }
    return array ;
}

module.exports = router
